const std = @import("std");
const api = @import("api.zig");

// 能力类型枚举
pub const CapabilityType = enum {
    memory,
    cpu,
    io,
    interrupt,
    // 更多能力类型...
};

// 能力权限枚举
pub const CapabilityPermission = enum {
    read,
    write,
    execute,
    // 更多权限类型...
};

// 能力结构
const Capability = struct {
    id: api.CapabilityId,
    type: CapabilityType,
    owner_id: u64, // 拥有者ID
    permissions: struct {
        read: bool = false,
        write: bool = false,
        execute: bool = false,
    },
    // 资源特定数据（根据能力类型不同而不同）
    resource_data: union(enum) {
        memory: struct {
            base: api.PhysicalAddress = 0,
            size: u64 = 0,
        },
        cpu: struct {
            priority: u32 = 0,
        },
        io: struct {
            port_start: u16 = 0,
            port_end: u16 = 0,
        },
        interrupt: struct {
            irq_start: u32 = 0,
            irq_end: u32 = 0,
        },
        none: void,
    },
};

// 能力管理器
pub const CapabilityManager = struct {
    allocator: std.mem.Allocator,
    capabilities: std.ArrayList(Capability),
    next_cap_id: api.CapabilityId = 1, // 能力ID从1开始，0表示无效
    service_layer_mem_cap: api.CapabilityId = 0,
    service_layer_cpu_cap: api.CapabilityId = 0,

    // 初始化能力管理器
    pub fn init(allocator: std.mem.Allocator) CapabilityManager {
        return CapabilityManager{
            .allocator = allocator,
            .capabilities = std.ArrayList(Capability).init(allocator),
        };
    }

    // 创建初始根能力
    pub fn initRootCapabilities(_: *CapabilityManager) !void {
        // 创建初始根能力
        // 在实际系统中，这些能力会在启动时创建并授予引导加载程序或初始服务
        std.log.info("Initializing root capabilities", .{});
    }

    // 设置服务层能力
    pub fn setServiceLayerCapabilities(
        self: *CapabilityManager,
        mem_cap: api.CapabilityId,
        cpu_cap: api.CapabilityId,
    ) void {
        self.service_layer_mem_cap = mem_cap;
        self.service_layer_cpu_cap = cpu_cap;
        std.log.info("Service layer capabilities set: mem_cap={}, cpu_cap={}", .{mem_cap, cpu_cap});
    }

    // 获取服务层初始能力
    pub fn getServiceLayerCapabilities(
        self: *CapabilityManager,
        out_mem_cap: *api.CapabilityId,
        out_cpu_cap: *api.CapabilityId,
    ) bool {
        if (self.service_layer_mem_cap == 0 or self.service_layer_cpu_cap == 0) {
            return false;
        }

        out_mem_cap.* = self.service_layer_mem_cap;
        out_cpu_cap.* = self.service_layer_cpu_cap;
        return true;
    }

    // 创建新能力 (别名方法)
    pub fn create_capability(
        self: *CapabilityManager,
        resource_data: anytype,
    ) !api.CapabilityId {
        return self.createCapability(resource_data);
    }

    // 创建新能力
    pub fn createCapability(
        self: *CapabilityManager,
        resource_data: anytype,
    ) !api.CapabilityId {
        const cap_id = self.next_cap_id;
        self.next_cap_id += 1;

        // 根据资源数据类型创建相应的能力
        const new_cap = Capability{
            .id = cap_id,
            .type = if (@typeInfo(@TypeOf(resource_data)) == .@"struct") blk: {
                // 确定能力类型
                if (@hasField(@TypeOf(resource_data), "size")) {
                    break :blk .memory;
                } else if (@hasField(@TypeOf(resource_data), "priority")) {
                    break :blk .cpu;
                } else if (@hasField(@TypeOf(resource_data), "port_start")) {
                    break :blk .io;
                } else if (@hasField(@TypeOf(resource_data), "irq_start")) {
                    break :blk .interrupt;
                } else {
                    break :blk @as(CapabilityType, @enumFromInt(0)); // 默认类型
                }
            } else .none,
            .owner_id = 0, // 初始拥有者为内核
            .permissions = .{ .read = true, .write = true, .execute = true }, // 初始权限
            .resource_data = if (@TypeOf(resource_data) == struct { type: CapabilityType, size: u64 }) blk: {
                // 内存资源
                break :blk .{ .memory = .{ .size = resource_data.size } };
            } else if (@TypeOf(resource_data) == struct { type: CapabilityType, priority: u32 }) blk: {
                // CPU资源
                break :blk .{ .cpu = .{ .priority = resource_data.priority } };
            } else blk: {
                break :blk .none;
            },
        };

        try self.capabilities.append(new_cap);
        std.log.info("Created new capability: id={}, type={}", .{cap_id, new_cap.type});

        return cap_id;
    }

    // 获取能力
    pub fn acquireCapability(self: *CapabilityManager, cap_id: api.CapabilityId) bool {
        for (self.capabilities.items) |*cap| {
            if (cap.id == cap_id) {
                // 在实际系统中，这里会增加引用计数并检查权限
                std.log.info("Capability acquired: id={}", .{cap_id});
                return true;
            }
        }

        std.log.warn("Failed to acquire capability: id={} not found", .{cap_id});
        return false;
    }

    // 释放能力
    pub fn releaseCapability(_: *CapabilityManager, cap_id: api.CapabilityId) void {
        // 在实际系统中，这里会减少引用计数
        // 当引用计数为零时，可能会回收资源
        std.log.info("Capability released: id={}", .{cap_id});
    }

    // 检查能力权限
    pub fn checkCapabilityPermission(
        self: *CapabilityManager,
        cap_id: api.CapabilityId,
        resource_type: api.ResourceType,
        permission: CapabilityPermission,
    ) bool {
        for (self.capabilities.items) |cap| {
            if (cap.id == cap_id) {
                // 检查资源类型是否匹配
                const cap_type = switch (resource_type) {
                    .memory => CapabilityType.memory,
                    .cpu => CapabilityType.cpu,
                    .io => CapabilityType.io,
                    .interrupt => CapabilityType.interrupt,
                };

                if (cap.type != cap_type) {
                    std.log.warn("Capability type mismatch: expected={}, got={}", .{cap_type, cap.type});
                    return false;
                }

                // 检查权限
                const has_permission = switch (permission) {
                    .read => cap.permissions.read,
                    .write => cap.permissions.write,
                    .execute => cap.permissions.execute,
                };

                if (!has_permission) {
                    std.log.warn("Capability permission denied: id={}, permission={}", .{cap_id, permission});
                }

                return has_permission;
            }
        }

        std.log.warn("Capability not found: id={}", .{cap_id});
        return false;
    }

    // 派生新能力（从现有能力创建限制性更强的能力）
    pub fn deriveCapability(
        self: *CapabilityManager,
        parent_cap_id: api.CapabilityId,
        _: struct { read: bool, write: bool, execute: bool },
        _: anytype,
    ) !api.CapabilityId {
        // 在实际系统中，这里会：
        // 1. 检查父能力是否存在且有效
        // 2. 检查请求的权限是否不超过父能力的权限
        // 3. 检查请求的资源子集是否在父能力的资源范围内
        // 4. 创建并返回新能力
        std.log.info("Deriving new capability from parent: id={}", .{parent_cap_id});
        return self.next_cap_id; // 模拟返回值
    }

    // 清理资源
    pub fn deinit(self: *CapabilityManager, _: std.mem.Allocator) void {
        self.capabilities.deinit();
        std.log.info("Capability manager deinitialized", .{});
    }
};

// 全局能力管理器实例（用于API访问）
pub var global_capability_manager: CapabilityManager = undefined;